package top.z.template.parse.ast.expression;

import top.z.template.Context;
import top.z.template.Template;
import top.z.template.parse.Ast.Expression;
import top.z.template.parse.Span;

import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Map
 */
public class MapLiteral extends Expression {

    private final List<Span>       key;
    private final List<Expression> value;

    public MapLiteral(Span span, List<Span> key, List<Expression> value) {
        super(span);
        this.key = key;
        this.value = value;
    }

    public List<Span> getKey() {
        return key;
    }

    public List<Expression> getValue() {
        return value;
    }

    @Override
    public Object evaluate(Template template, Context context, OutputStream out) throws IOException {
        Map<String, Object> map = new HashMap<>();
        for (int i = 0, n = key.size(); i < n; i++) {
            Object value = this.value.get(i).evaluate(template, context, out);
            map.put(key.get(i).getText(), value);
        }
        return map;
    }
}
